package com.delio.client.produccion.valesalidas;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.delio.client.idioma.DelioConstants;
import com.delio.client.produccion.articulos.Articulos;
import com.delio.client.produccion.detallevalesalidas.DetalleValeSalidas;
import com.delio.client.produccion.motivos.Motivos;
import com.delio.client.produccion.ordenproducciones.SearchOrdenProduccionIPForm;
import com.delio.client.util.ComboboxFieldBinding;
import com.extjs.gxt.ui.client.Style.ButtonArrowAlign;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.binding.FieldBinding;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ButtonBar;
import com.extjs.gxt.ui.client.widget.button.SplitButton;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.form.HiddenField;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.filters.GridFilters;
import com.extjs.gxt.ui.client.widget.grid.filters.StringFilter;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.menu.Menu;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;

public class InsumosProduccionForm extends Dialog{
	private DelioConstants x = GWT.create(DelioConstants.class);
	public Button btnDeleteValeSalida;
	SplitButton btnGuardar;
	ToolBar toolBar;
	ContentPanel cpi,cpw;
	BorderLayoutData sup,inf,center,c,north;
	public static TextField<String> ordenproduccion;
	ComboBox<ModelData> articulo;
	ComboBox<BeanModel> motivo;
	DateField fecha;
	HiddenField<String> id=null,ordenproduccion_id;
	NumberField cantidad; 
	private FormBinding formbinding;
	FormPanel fp;
	private BeanModel selectedModel;
	Integer idmotivo,idarticulo;//,idvalesalida;
	Menu contMenuOP;
	MenuItem miOP;
	public Integer ipf_idordenproduccion;
	Integer iddetallevalesalida;
	
	public InsumosProduccionForm(){
	    setBodyBorder(false);  
		setHeading("Insumos en Produccion");  
		setWidth(580);  
		setHeight(600);
		setPosition(65, 65);
		this.setPosition(400, 65);
		setModal(true);
		    
		setButtons("");
		setFrame(true);
		setHeaderVisible(true);
		setLayout(new BorderLayout());
		 
        Motivos.getStore();
		ValeSalidas.getPaginate();
	    DetalleValeSalidas.getPaginate();
	    Articulos.getStore();
       	formulario();
       	
        cpw = new ContentPanel();
	    cpw.setHeading("Editar Insumos de Produccion");
	    cpw.setIconStyle("images/icons/people.png");
	    cpw.setLayout(new FitLayout());
	    
	    cpw.add(fp);
	    
	    center  = new BorderLayoutData(LayoutRegion.CENTER);
	    center.setMargins(new Margins(0,2,2,0));
	    center.setCollapsible(true);

		 
		cpi = new ContentPanel();
		cpi.setHeaderVisible(false);
		cpi.setHeading("Listado de Insumos en Produccion");
		cpi.setIconStyle("images/icons/table.png");
		cpi.setLayout(new BorderLayout());
		cpi.setLayout(new FitLayout());
		
		c = new BorderLayoutData(LayoutRegion.CENTER);

	
		north  = new BorderLayoutData(LayoutRegion.NORTH,350);
		north.setMargins(new Margins(0,2,0,0));
	 	
	    final PagingToolBar toolBarPag = new PagingToolBar(10);
        toolBarPag.bind(ValeSalidas.loader);
        
        List<ColumnConfig> conf = new ArrayList<ColumnConfig>();
        CheckBoxSelectionModel<BeanModel> sm = new CheckBoxSelectionModel<BeanModel>();
    
        conf.add(sm.getColumn()); 
        ColumnConfig col  = new ColumnConfig("opcodigo",x.ordenproduccion(),100);
	    conf.add(col);
	    col  = new ColumnConfig("motdescripcion",x.motivo(),100);
	    conf.add(col);
	    col  = new ColumnConfig("fecha",x.fecha(),100);
	    conf.add(col);
	    col  = new ColumnConfig("artcodigo",x.articulos(),100);
	    conf.add(col);
	    col  = new ColumnConfig("artdescripcion",x.articulos(),100);
	    conf.add(col);
	    col  = new ColumnConfig("cantidad",x.cantidad(),100);
	    conf.add(col);
	    
	    final ColumnModel cm = new ColumnModel(conf);
	    
	    Grid<BeanModel> grid = new Grid<BeanModel>(ValeSalidas.store, cm);  
        grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {  
          public void handleEvent(GridEvent<BeanModel> be) {  
        	  ValeSalidas.loader.load(0, 10);  
          }  
        }); 
        sm.setSelectionMode(SelectionMode.SINGLE);
        grid.setSelectionModel(sm);
        grid.getSelectionModel().addListener(Events.SelectionChange,
           new Listener<SelectionChangedEvent<BeanModel>>() {
			@Override
			public void handleEvent(SelectionChangedEvent<BeanModel> be) {		
    		   if(be.getSelection().size() == 1) {
	             formbinding.bind((BeanModel) be.getSelection().get(0));
	             selectedModel = be.getSelectedItem();
	             //ipf_idordenproduccion = Integer.parseInt(selectedModel.get("ordenproduccion_id").toString());
	             iddetallevalesalida  =   Integer.parseInt(selectedModel.get("iddetallevalesalida").toString());
	             System.out.println("iddetallevalesalida="+iddetallevalesalida);
  	           }
    			if(be.getSelection().size()==0){
                 clearForm();
                 formbinding.unbind();
               }
    			if(be.getSelection().size()>1)
    			 formbinding.unbind();
			}
          });
        
        grid.setLoadMask(true);  
        grid.setBorders(true);       
        
        GridFilters filters = new GridFilters();
        StringFilter OPFilter = new StringFilter("opcodigo");        
        StringFilter motivoFilter = new StringFilter("motdescripcion");
        StringFilter fechaFilter = new StringFilter("fecha");
        StringFilter artcodigoFilter = new StringFilter("artcodigo");
        StringFilter artdescripcionFilter = new StringFilter("artdescripcion");
        StringFilter cantidadFilter = new StringFilter("cantidad");

          
        filters.addFilter(OPFilter);        
        filters.addFilter(motivoFilter);        
        filters.addFilter(fechaFilter);        
        filters.addFilter(artcodigoFilter);
        filters.addFilter(artdescripcionFilter);
        filters.addFilter(cantidadFilter);

        grid.addPlugin(filters);                
        grid.addPlugin(sm);
        formbinding = new FormBinding(fp);
        formbinding.setStore(ValeSalidas.store);
        formbinding.addFieldBinding(new FieldBinding(id,"id"));
        formbinding.addFieldBinding(new FieldBinding(ordenproduccion,"opcodigo"));
        formbinding.addFieldBinding(new FieldBinding(ordenproduccion_id,"idordenproduccion"));
	    formbinding.addFieldBinding(new ComboboxFieldBinding(motivo,"motdescripcion"));
	    formbinding.addFieldBinding(new FieldBinding(fecha,"fecha"));
	    formbinding.addFieldBinding(new ComboboxFieldBinding(articulo,"artdescripcion"));
	    formbinding.addFieldBinding(new FieldBinding(cantidad,"cantidad"));
	    
	    toolBar = new ToolBar(); 
        btnDeleteValeSalida = new Button("Eliminar", IconHelper.createPath("images/icons/delete.gif"));
        btnDeleteValeSalida.setEnabled(false);
        toolBar.add(btnDeleteValeSalida);
        btnDeleteValeSalida.addSelectionListener(new SelectionListener<ButtonEvent>(){
    	   public void componentSelected(ButtonEvent ce){
			  if(id.getValue() != null){	 
			    Listener<MessageBoxEvent> callback = new Listener<MessageBoxEvent>() {	 
				  public void handleEvent(MessageBoxEvent be) {
		           if (be.getButtonClicked().getItemId().equals(Dialog.YES)) { 
				        ValeSalidas.eliminar(Integer.parseInt(id.getValue()));
					    ValeSalidas.loader.load();
			         }
		            }
			       };
			       String msg = "Esta seguro que desea eliminar al Cliente?";
			       MessageBox.confirm(x.eliminarCliente(), msg, callback);
			 	  }else{
				   MessageBox.alert(x.seleccionar(), "Seleccione una fila porfavor", null);
			      }
			 }
		  });
        
	    contMenuOP = new Menu();  
	    miOP = new MenuItem();  
	    miOP.setText("Buscar Orden Produccion");  
	    miOP.setIconStyle("images/icons/search_lupa.png");  
	    miOP.addSelectionListener(new SelectionListener<MenuEvent>() {  
	    public void componentSelected(MenuEvent ce) {  
	      SearchOrdenProduccionIPForm opipf = new SearchOrdenProduccionIPForm();
	      opipf.show();
	      }  
	    });  
	    contMenuOP.add(miOP);  
	    ordenproduccion.setContextMenu(contMenuOP); 
               
     	cpi.setTopComponent(toolBar);
	    cpi.add(grid,c);
	    cpi.setBottomComponent(toolBarPag);	
	    
	    add(cpi,north);
	    add(cpw,center);
	    
	}
	
	private Menu createMenu() {  
	   Menu menu = new Menu();  
	   menu.add(new MenuItem("Editar"));  
	   menu.add(new MenuItem("Guardar"));  
	  return menu;  
	}
 
	public ButtonBar bbutonbar(){
	
		  ButtonBar bb = new ButtonBar();
			
		  btnGuardar = new SplitButton();  
	      btnGuardar.setMenu(createMenu());  
	      btnGuardar.setArrowAlign(ButtonArrowAlign.BOTTOM);  
		  btnGuardar.setText("Elegir");
		 
		  //btnGuardar = new Button("Guardar",IconHelper.createPath("images/icons/save_all.png"));
	      btnGuardar.setSize(100, 30);
		  btnGuardar.addSelectionListener(new SelectionListener<ButtonEvent>(){
		   public void componentSelected(ButtonEvent ve){
			   if(validate()&&validarId()){  
				final ValeSalida vs = new ValeSalida();
				  vs.setIdtipodocumento(null);
				  vs.setIdmotivo(idmotivo);
				  vs.setIdordenproduccion(ipf_idordenproduccion); 
			      vs.setFecha(fecha.getValue());
			      
			      vs.setIdarticulo(idarticulo);
			      vs.setCantidad(cantidad.getValue().doubleValue());
			      vs.setIddetallevalesalida(iddetallevalesalida);
				 if(id.getValue() == null){	
			       ValeSalidas.guardar(vs);
			       System.out.println("impresion del server vs.getId()="+vs.getId());
			       ValeSalidas.loader.load();
			       clearForm();
			     }
			     if(id.getValue() != null){
				 Listener<MessageBoxEvent> callback = new Listener<MessageBoxEvent>() {	 
				  public void handleEvent(MessageBoxEvent be) {
				    if(be.getButtonClicked().getItemId().equals(Dialog.YES)) {  
				     vs.setId(Integer.parseInt(id.getValue()));
				     vs.setIdordenproduccion(Integer.parseInt(ordenproduccion_id.getValue()));
				     
				     System.out.println("ordenproduccion_id="+Integer.parseInt(ordenproduccion_id.getValue()));
				     System.out.println("cantidad="+cantidad.getValue());
					 ValeSalidas.actualizar(vs);
					 ValeSalidas.loader.load();
					}
					}
			      };
			      String msg = "Esta seguro que desea Actualizar el Cliente?";
			      MessageBox.confirm("Actualizar Cliente?", msg, callback);
			 	  }
		        }
			  }
	       });
	
		  HorizontalAlignment align =  HorizontalAlignment.CENTER;
		  bb.add(btnGuardar);
		  bb.setAlignment(align);
		  return bb;
	  }
	 
	public boolean validate(){
	  return fp.isValid();
	}
	
	public boolean validarId(){
		boolean var=false;
		Integer idmot=null,idop=null,idart=null,idopclass=null;
		idmot      = idmotivo;
		idop       = ipf_idordenproduccion;
		idart      = idarticulo;
		idopclass  = Integer.parseInt(ordenproduccion_id.getValue());
		if(idmot!=null&&idart!=null&&(idop!=null||idopclass!=null))
		  var = true;
		System.out.println("idmot="+idmot+" idop="+idop+" idart="+idart);
	  System.out.println("los ids son de tipo...."+var);	
	  return var;
	}
	 
			  
	public void formulario(){
		fp = new FormPanel();
		fp.setHeaderVisible(false);
		fp.setFrame(true);
	   	FormData formData = new FormData("100%");  
	    fp.setFrame(true);  
	    fp.setSize(600, -1);  
	    fp.setLabelAlign(LabelAlign.TOP);  
	    fp.setButtonAlign(HorizontalAlignment.CENTER);
		
	    LayoutContainer main = new LayoutContainer();  
	    main.setLayout(new ColumnLayout()); 
	    
	    LayoutContainer left = new LayoutContainer();  
	    left.setStyleAttribute("paddingRight", "10px");  
	    FormLayout layout = new FormLayout();  
	    layout.setLabelAlign(LabelAlign.TOP);  
	    left.setLayout(layout); 
	    
	    
	    LayoutContainer right = new LayoutContainer();  
	    right.setStyleAttribute("paddingLeft", "10px");  
	    layout = new FormLayout();  
	    layout.setLabelAlign(LabelAlign.TOP);  
	    right.setLayout(layout); 
	    
		id = new HiddenField<String>();
		id.setVisible(false);
		left.add(id, formData);
		
		ordenproduccion_id = new HiddenField<String>();
		ordenproduccion_id.setVisible(false);
		
		left.add(ordenproduccion_id, formData);
		
    	ordenproduccion = new TextField<String>();
		ordenproduccion.setFieldLabel(x.ordenproduccion());
		ordenproduccion.setAllowBlank(false);
	
		left.add(ordenproduccion, formData);
		
		motivo = new ComboBox<BeanModel>();
		motivo.setEmptyText("Select a state...");  
	    motivo.setAllowBlank(false);
	    motivo.setDisplayField("descripcion");  
	    motivo.setFieldLabel(x.motivo());
	    motivo.setWidth(150);  
	    motivo.setStore(Motivos.storeCombo);
	    motivo.setValueField("descripcion");
	    motivo.setTypeAhead(true);  
	    motivo.setTriggerAction(TriggerAction.ALL); 
	    motivo.addSelectionChangedListener(new SelectionChangedListener<BeanModel>(){
	    public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
	      if(motivo.getValue()!=null){	
 		   idmotivo  = Integer.parseInt(motivo.getValue().get("id").toString());
 		  }
         }
	    });
	    
	    left.add(motivo,formData);
		
	    fecha = new DateField();
		fecha.setName("fecha");
		fecha.getPropertyEditor().setFormat(DateTimeFormat.getFormat("dd/MM/yyyy"));
		fecha.setAllowBlank(false);
		fecha.setFieldLabel(x.fecha());
		fecha.setValue(new Date());
		
		left.add(fecha,formData);
		
		articulo = new ComboBox<ModelData>();
		articulo.setEmptyText("Select a state...");  
	    articulo.setAllowBlank(false);
	    articulo.setDisplayField("descripcion");  
	    articulo.setFieldLabel(x.articulos());
	    articulo.setWidth(150);  
	    articulo.setStore(Articulos.storeCombo);
	    articulo.setValueField("descripcion");
	    articulo.setTypeAhead(true);  
	    articulo.setTriggerAction(TriggerAction.ALL); 
	    articulo.addSelectionChangedListener(new SelectionChangedListener<ModelData>(){
	    public void selectionChanged(SelectionChangedEvent<ModelData> se) {
	      if(articulo.getValue()!=null){	
 		   idarticulo  = Integer.parseInt(articulo.getValue().get("id").toString());
 		  }
         }
	    });	
	    right.add(articulo, formData);  
		
	    cantidad = new NumberField();
	    cantidad.setFieldLabel(x.cantidad());
	    right.add(cantidad, formData);  
	    right.add(bbutonbar(), formData);  
		    
	    main.add(left, new ColumnData(.5));  
	    main.add(right, new ColumnData(.5));  
	    
	    fp.add(main, new FormData("100%"));  

/*	    fp.add(id);	
	    fp.add(ordenproduccion,new FormData("-20"));
		fp.add(motivo,new FormData("-20"));
		fp.add(fecha,new FormData("-20"));
		fp.add(articulo,new FormData("-20"));
		fp.add(cantidad,new FormData("-20"));
        fp.add(bbutonbar());*/
/*      Utilities.setLengh(ordenproduccion, motivo, 60);
        Utilities.setLengh(motivo, fecha, 60);
        Utilities.setLengh(fecha, articulo, 60);
        Utilities.setNumerosEnteros(cantidad);
*/
	}
	
   public void clearForm(){
	   fp.clear();
    }
}
